package com.bnlr.lrparking.appui.mine.personal;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bnlr.lrparking.constant.ConstantFlag;
import com.bnlr.lrparking.constant.LrConstant;
import com.bumptech.glide.Glide;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.util.BitmapHelper;
import com.bnlr.lrparking.util.Tools;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 个人资料页面
 * <p>
 * Created by Administrator on 2017/2/15.
 */
@RuntimePermissions
public class PersonInfoActivity extends BaseActivity {
    @BindView(R.id.person_photo)
    ImageView personPhoto;
    @BindView(R.id.ll_psInfo_photo)
    LinearLayout llPsInfoPhoto;
    @BindView(R.id.person_nickname)
    TextView personNickname;
    @BindView(R.id.ll_psInfo_nickname)
    LinearLayout llPsInfoNickname;
    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.tv_nav_right)
    TextView tvNavRight;
    @BindView(R.id.iv_nav_right)
    ImageView ivNavRight;
    @BindView(R.id.iv_nav_back)
    ImageView ivNavBack;
    @BindView(R.id.ll_psInfo_pwd)
    LinearLayout llPsInfoPwd;
    @BindView(R.id.person_phone)
    TextView personPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personinfo);
        ButterKnife.bind(this);
        tvNavTitle.setText("个人资料");
        init_title();

    }

    public void init_title() {
        Glide.with(this)
                .load(AppConfig.getInstance().getString("photo", ""))
                .bitmapTransform(new CropCircleTransformation(this))
                .placeholder(R.mipmap.personal_head)
                .error(R.mipmap.personal_head)
                .into(personPhoto);

        String mobile = AppConfig.getInstance().getString("userName", "");
        if (mobile.length()== ConstantFlag.INTEGER_FLAG_ELEVEN){
            String maskNumber = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
            personPhone.setText(maskNumber);
        }else {
            personPhone.setText(mobile);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        personNickname.setText(AppConfig.getInstance().getString("nickName", ""));
    }

    private int TAG;

    @Override
    public void doClick(View v) {
        Log.i("TAG", "onclick");
        super.doClick(v);
        switch (v.getId()) {
            case R.id.person_nickname:   // 修改昵称
                Log.i("TAG", "onclick  person_nickname");
                startActivity(AlterNickNameActivity.class);
                break;
            case R.id.ll_psInfo_pwd:     // 修改用户密码
                Log.i("TAG", "onclick  ll_psInfo_pwd");
                startActivity(ChangePwdActivity.class);
                break;
            case R.id.ll_psInfo_photo:   // 修改头像
                new AlertView.Builder().setContext(baseContext)
                        .setStyle(AlertView.Style.ActionSheet)
                        .setTitle("请选择上传方式")
                        .setMessage(null)
                        .setCancelText("取消")
                        .setDestructive("拍照", "从相册中选择")
                        .setOthers(null)
                        .setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                switch (position) {
                                    case 0:
                                        TAG = 1;
                                        PersonInfoActivityPermissionsDispatcher.onNeedWithCheck(PersonInfoActivity.this);
                                        break;
                                    case 1:
                                        TAG = 2;
                                        PersonInfoActivityPermissionsDispatcher.onNeedWithCheck(PersonInfoActivity.this);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                        .build()
                        .show();
                break;
            default:
                break;
        }
    }

    private void sendLogo(final String paths) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "UpdatePhotoByUserId");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("img", logo);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<JSONObject>(baseContext, true, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    Glide.with(baseContext).load(paths).bitmapTransform(new CropCircleTransformation(PersonInfoActivity.this)).into(personPhoto);
                                    CommonUtil.showToask(baseContext, "修改成功");
                                    AppConfig.getInstance().putString("photo", obj.getJSONObject("data").getString("img"));
                                    //finish();
                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 102:
                    startPhotoZoom(Uri.fromFile(mFile));
                    break;
                case 101:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case 103:
                    if (data != null) setPicToView(data);
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            throw new RuntimeException("The uri is not exist.");
        }
        Intent intent = new Intent(this, CropperActivity.class);
        intent.putExtra("path", Tools.getRealFilePath(this, uri));
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        startActivityForResult(intent, 103);
    }

    private String logo = "";
    private File mFile;

    private void setPicToView(Intent picdata) {
        if (picdata == null) {
            return;
        }
        String path = picdata.getStringExtra("path");
        Log.e("touxinag", path);
        if (path != null) {
            try {

                logo = CommonUtil.bitmapToBase64(BitmapHelper.getImage(path, 200));
                Log.e("imageUrl", logo);
                sendLogo(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNeed() {
        if (TAG == 1) {
            File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "lirentingche");
            if (!dir.exists()) dir.mkdirs();
            mFile = new File(dir, "/image_" + System.currentTimeMillis() + ".jpg");
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri imageUri = FileProvider.getUriForFile(baseContext, "com.bnlr.lrparking.fileprovider", mFile);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                // openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Tools.getImageContentUri(baseContext, file));
                startActivityForResult(openCameraIntent, 102);
            } else {
                // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(openCameraIntent, 102);
            }
        }
        if (TAG == 2) {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 101); // 适用于4.4及以上android版本
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PersonInfoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onRationale(final PermissionRequest request) {


        final MaterialDialog materialDialog = new MaterialDialog(this);
        materialDialog.content("需要调用系统相机拍摄图片或视频")
                .title("需要权限")
                .btnText("取消", "确定")
                .showAnim(new BounceTopEnter())
                .show();
        materialDialog.setOnBtnClickL(
                new OnBtnClickL() { //left btn click listener
                    @Override
                    public void onBtnClick() {
                        materialDialog.dismiss();
                        request.cancel();
                    }
                },
                new OnBtnClickL() { //right btn click listener
                    @Override
                    public void onBtnClick() {
                        materialDialog.dismiss();
                        request.proceed();
                    }
                });
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onDenied() {
        //用户拒绝了权限
        CommonUtil.showToask(this, "请求权限被拒绝，请重新开启权限");

    }
}